package com.baizan.daka

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.content.FileProvider
import com.baizan.daka.mvp.model.bean.AppVerSionBean
import com.baizan.daka.rx.Subscriber.CommonSubscriber
import com.baizan.daka.util.AppUtils
import com.baizan.daka.util.PermissionDialogUtils
import com.baizan.daka.util.SchedulerUtils
import com.dianzan.daka.R
import com.hazz.kotlinmvp.net.RetrofitManager
import com.tbruyelle.rxpermissions.RxPermissions
import io.reactivex.disposables.CompositeDisposable
import rx.Observable
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL

class AppUpdateManager(val mContext: Activity) {

    var isChecked = false //是否检查过 app 更新

    var dialog: Dialog? = null

    /* 下载包安装路径/cnbsf/bsf/apk */
    var mPath = Constants.DIR_APK

    /**
     * 应用名字
     */
    private var mFileName: String? = null
    private var mProgress: ProgressBar? = null
    private var downloadTv: TextView? = null
    private var dialogTitle: TextView? = null
    private var btnDownload: TextView? = null
    private var rlProgress: View? = null
    private val DOWN_UPDATE = 1
    private val DOWN_OVER = 2
    private val ERROR = 3
    private var progress = 0
    private var downLoadThread: Thread? = null
    private var interceptFlag = false

    val FILE_INCOMPLETE = 5
    var listener: OnUpdateAppListener? = null


    private val mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                DOWN_UPDATE -> {
                    mProgress?.progress = progress
                    downloadTv?.text = "已下载$progress%"
                }
                DOWN_OVER -> {
                    dialog?.let {
                        if (it.isShowing) {
                            it.dismiss()
                            dialog = null
                        }
                    }
                    installApk()
                }
                ERROR -> {
                    val f = File(mPath + mFileName)
                    if (f.exists()) {
                        f.delete()
                    }
                    showToast("服务器异常，请稍候重试")
                    btnDownload?.visibility = View.VISIBLE
                }
                FILE_INCOMPLETE -> showToast("下载失败！")
            }
        }
    }


    //#############################    更新  startUrl  #######################################

    //#############################    更新  startUrl  #######################################
    fun setOnUpdateAppListener(listener: OnUpdateAppListener?) {
        this.listener = listener
    }

    /**
     * 请求 更新
     *
     * @param mCompositeSubscription
     */
    fun checkApkVersion(mCompositeSubscription: CompositeDisposable) {
        if (isChecked) return
        // 判断网络是否连接
        RetrofitManager.service.getAppUpdate()
            .compose(SchedulerUtils.ioToMain())
            .subscribe(object : CommonSubscriber<AppVerSionBean>(mCompositeSubscription) {

                override fun onCallLogin(error: String) {

                }

                override fun onCallCompleted() {
                    super.onCallCompleted()
                    isChecked = true
                }

                override fun onCallNext(appCheck: AppVerSionBean?) {
                    appCheck?.let {
                        if (it.appVersion.toInt() > AppUtils.getVerCode(mContext)) {
                            listener?.onUpdate(it)
                        }else{
                            listener?.onNoupdate()
                        }
                    } ?: let {
                        listener?.onNoupdate()
                    }

                }

                override fun onCallError(e: String) {
                    super.onCallError(e)
                    listener?.onNoupdate()
                }
            })


    }


//#############################    更新  end  #######################################


    //#############################    更新  end  #######################################
   fun showUpdataInfo(mUpdateInfo: AppVerSionBean) {
        // 显示更新提示框
        mFileName = "baizandaka" + ".apk"
        showUpdateDialog(mUpdateInfo)
    }

    private fun showUpdateDialog(updateInfo: AppVerSionBean) {
        if (mContext.isFinishing) {
            return
        }
        dialog?.let {
            if (it.isShowing) return
        }
        try {
            val dialog = Dialog(mContext)
            val inflater = LayoutInflater.from(mContext)
            val v: View = inflater.inflate(R.layout.update_dialog, null)
            mProgress = v.findViewById<View>(R.id.pb_update_dialog) as ProgressBar
            rlProgress = v.findViewById(R.id.rl_progress)
            btnDownload =
                v.findViewById<View>(R.id.btn_download_update_dialog) as TextView
            downloadTv = v.findViewById<View>(R.id.download_tv) as TextView
            dialogTitle =
                v.findViewById<View>(R.id.tv_title_update_dialog) as TextView
            dialogTitle?.text = "发现新版本v" + updateInfo.appVersion
            btnDownload?.setOnClickListener {
                val rxPermissions2 = RxPermissions((mContext as Activity?)!!)
                Observable.just(Any())
                    .compose(rxPermissions2.ensureEach(Manifest.permission.READ_EXTERNAL_STORAGE))
                    .compose(rxPermissions2.ensureEach(Manifest.permission.WRITE_EXTERNAL_STORAGE))
                    .subscribe { permission ->
                        if (permission.granted) {
                            // 用户允许权限
                            rlProgress?.visibility = View.VISIBLE
                            dialogTitle?.text = "正在更新"
                            btnDownload?.visibility = View.GONE
                            downloadApk(updateInfo)
                        } else {
                            mAlertDialog?.let {
                                if (!it.isShowing) {
                                    it.show()
                                }
                            } ?: let {
                                mAlertDialog = PermissionDialogUtils().showMyDialog(
                                    (mContext as Activity?)!!,
                                    "进入权限设置界面开启-存储权限"
                                )
                            }
                        }
                    }
            }
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
            dialog.setContentView(v)
            dialog.window.setBackgroundDrawableResource(R.color.transparent)
            val width: Int = AppUtils.getScreenWidth(mContext) - AppUtils.dp2px(100)
            val params = dialog!!.window.attributes
            params.width = width
            params.height = WindowManager.LayoutParams.WRAP_CONTENT
            dialog.window.attributes = params
            dialog.setCancelable(false)
            dialog.show()
            this.dialog = dialog
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    var mAlertDialog: AlertDialog? = null

    /**
     * 下载apk
     */
    private fun downloadApk(updateInfo: AppVerSionBean) {
        try {
            val file = File(mPath)
            if (!file.exists()) {
                file.mkdirs()
            }
            val mThread = Thread(mRunnable(updateInfo))
            mThread.start()
            this.downLoadThread = mThread
        } catch (e: Exception) {
        }
    }

    inner class mRunnable(private val updateInfo: AppVerSionBean) : Runnable {
        override fun run() {
            try {
                val url = URL(updateInfo.appUrl)
                val conn: HttpURLConnection
                conn = url.openConnection() as HttpURLConnection
                conn.connect()
                val length = conn.contentLength
                deleteAllFiles(File(mPath))
                val apkFile = File(mPath + mFileName)
                if (!apkFile.exists()) {
                    apkFile.createNewFile()
                }
                val input = conn.inputStream
                val fos = FileOutputStream(apkFile)
                var count = 0
                val buf = ByteArray(1024)
                do {
                    val size = input.read(buf)
                    if (size > 0) {
                        count += size
                        progress = (count * 100f / length).toInt()
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWN_UPDATE)
                        fos.write(buf, 0, size)
                    }
                    if (count == length) {
                        // 下载完成通知安装
                        progress = 100
                        mHandler.sendEmptyMessage(DOWN_UPDATE)
                        mHandler.sendEmptyMessage(DOWN_OVER)
                        break
                    }
                } while (!interceptFlag) // 点击取消就停止下载.
                if (interceptFlag) { //点击取消，删除不完整的apk文件
                    val f = File(mPath + mFileName)
                    if (f.exists()) {
                        f.delete()
                    }
                }
                fos.close()
                input.close()
            } catch (e: MalformedURLException) {
                e.printStackTrace()
                mHandler.sendEmptyMessage(ERROR)
            } catch (e: IOException) {
                e.printStackTrace()
                mHandler.sendEmptyMessage(ERROR)
            } catch (e: Exception) {
                mHandler.sendEmptyMessage(ERROR)
            }
        }

    }


    /**
     * 安装apk
     */
    private fun installApk() {
        val apkFile = File(mPath + mFileName)
        if (!apkFile.exists()) {
            return
        }
        val intent = Intent(Intent.ACTION_VIEW)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK //如果不加，最后安装完成，点打开，无法打开新版本应用。
        val data: Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            data = FileProvider.getUriForFile(
                mContext, Constants.MY_PROVIDER, apkFile
            )
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        } else {
            data = Uri.fromFile(apkFile)
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive")
        mContext.startActivity(intent)
        Log.e("installApk =", "" + apkFile.absolutePath)
        mContext.finish()
        // 网上说要加这句，但是测试加了这句在华为手机上出现了问题。 还是不要加
//        android.os.Process.killProcess(android.os.Process.myPid()); //如果不加，最后不会提示完成、打开。
        MyApp.clearnAll()
        isChecked = false
    }


    /**
     * 删除目录下所有文件
     *
     * @param root
     */
    private fun deleteAllFiles(root: File) {
        val files = root.listFiles()
        if (files != null) for (f in files) {
            if (f.path == mPath + mFileName) {
                if (f.isDirectory) { // 判断是否为文件夹
                    deleteAllFiles(f)
                } else {
                    if (f.exists()) { // 判断是否存在
                        try {
                            f.delete()
                        } catch (e: Exception) {
                        }
                    }
                }
            }
        }
    }

    interface OnUpdateAppListener {
        /**
         * @param isToDownLoad 是否 去 下载更新
         */
        fun onUpdate(appCheck: AppVerSionBean)

        fun onNoupdate()
    }

}